package org.wang.jsch_session_pool.test;

import lombok.extern.slf4j.Slf4j;
import org.opengauss.jsch.pool.ExecOperations;
import org.opengauss.jsch.pool.JschSessionPool;
import org.opengauss.jsch.pool.config.SessionConfig;
import org.opengauss.jsch.pool.enums.ChannelType;

import java.util.Arrays;
import java.util.List;

@Slf4j
public class JschTest {
    /**
     * rely
     */
    private  static  final String DEPENDENCY
            = "yum list installed | egrep 'libaio-devel|flex|bison|ncurses-devel|glibc-devel|patch|readline-devel'";

    /**
     * base dependencies
     */
    private  static  final   String BASE_DEPENDENCY = "yum list installed | egrep 'coreutils|procps-ng|openssh-clients|unzip|lsof|grep|tar'";
    /**
     * base dependencies
     */
    private  static  final  String OPENEULER_BASE_DEPENDENCY = "yum list installed | egrep 'coreutils|procps-ng|openssh|unzip|lsof|grep|tar'";
    private static final List<String> cmdList = List.of(DEPENDENCY,BASE_DEPENDENCY, OPENEULER_BASE_DEPENDENCY);
    public static void main(String[] args) {
        // read start param ip ,port,user,pwd,cmdIdx
        // parse param and build param SessionConfig execConfig = new SessionConfig("119.3.170.242", 26262,"root", "Huawei@123").withChannelType(
        //            ChannelType.EXEC).withTimeout(15000);
        if (args.length != 5) {
            log.error("start param not valid {}", Arrays.toString(args));
            return;
        }
        int port = Integer.parseInt(args[1]);
        int cmdIdx = Integer.parseInt(args[4]);

        SessionConfig execConfig = new SessionConfig(args[0], port, args[2], args[3]).withChannelType(
                ChannelType.EXEC).withTimeout(15000);
        try {
            ExecOperations.ExecResult result = ExecOperations.executeCommand(execConfig, cmdList.get(cmdIdx));
            log.info("command exec result :{}", result);
            log.info("exit code: {}", result.getExitCode());
            log.info("output: \n{}", result.getOutput());
            log.info("error: \n{}", result.getError());
        } catch (Exception e) {
            log.error("execute single command failed", e);
        }
        // 关闭所有连接池（应用退出时调用）
        JschSessionPool.closeAllPools();
    }

}
